<template>
    <el-card class="form-card" shadow="hover">
        <el-form ref="formRef" :rules="rules" :model="form" style="width: 400px;">
            <el-form-item label="原密码" prop="password">
                <el-input show-password v-model="form.password" autocomplete="off" placeholder="请输入原密码" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <el-input show-password v-model="form.newPassword" autocomplete="off" placeholder="请输入新密码" />
            </el-form-item>
            <el-form-item label="确定新密码" prop="confirmPassword">
                <el-input show-password v-model="form.confirmPassword" autocomplete="off" placeholder="请确认新密码" />
            </el-form-item>
            <div style="text-align: center;">
                <el-button @click="update" size="large" type="primary">立即修改</el-button>
            </div>
        </el-form>
    </el-card>

</template>
<script setup>
import { useUserStore } from '@/store/userStore';
import { ref } from 'vue';
import { updatePasswordApi } from '@/api/updatePasswordApi';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

const userStore = useUserStore()
const router = useRouter()
const form = ref({})
const formRef = ref()
const validatePass = (rule , value , callback) => {
  if (!value) {
    callback(new Error('请再次确认密码：'))
  } else if (value !== form.value.newPassword) {
    callback(new Error("两次输入的密码不一致!"))
  } else {
    callback()
  }
}
const rules = {
    password: [
        { required: true, message: '请输入原密码', trigger: 'blur' },
        { min: 3, max: 10, message: '账号长度在 3 到 10 个字符', trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 3, max: 10, message: '账号长度在 3 到 10 个字符', trigger: 'blur' }
    ],   
    confirmPassword: [
        { validator: validatePass, trigger: 'blur' },
        { min: 3, max: 10, message: '账号长度在 3 到 10 个字符', trigger: 'blur' }
    ],
};
const update = () => {
    formRef.value.validate(async(valid) => {
    form.value.id = userStore.userInfo.id
    form.value.role = userStore.userInfo.role

    // console.log(userStore.userInfo);
    // console.log(form);
    
    if(userStore.userInfo?.role == 'EMP') {
            const res = await updatePasswordApi(form.value)
            if(res.code=='200') {
                ElMessage.success("修改成功!");
                userStore.clearUserInfo()
                router.replace({path: '/login'})
            } else {
                ElMessage.error(res.msg)
            }
        } else {
            const res = await updatePasswordApi(form.value)
            if(res.code == '200') {
                ElMessage.success("修改成功!");
                userStore.clearUserInfo()
                router.replace({path: '/login'})
            } else {
                ElMessage.error(res.msg)
            }        
        }        
    })
    

}
</script>